<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of TuanController
 *
 * @author taoheping
 */
class TuanController extends Uuch_BaseController {
    
    
    public function init() {
        
        
        
        parent::init();
        $this->checkLogin();
        $userid = $this->currentUser()->Id;
        $this->appendScript('/js/jquery.min.js');
        
        $admins =array('1','2','64','69','13152');
        if(!in_array($userid, $admins)){
            exit();
        }
    }
    
    public function homeAction(){
        $this->appendCss('/css/daigou/fill.css');
    }
    
    public function instoreAction(){
        $this->setTitle('添加产品入库');
        $this->appendScript('/js/jquery.validate.min.js')->appendScript('/js/messages_cn.js');
        $this->appendCss('/css/daigou/fill.css');
        if($this->getRequest()->isPost()){
            $item = new Application_Model_StoreItem();
            $item->ProductName = $this->getSafeParam('productName');
            $item->StoreId = $this->getSafeParam('storeno');
            $item->DateInStore = $this->now();
            $item->Quantity=1;
            $item->State = Application_Model_StoreItem::STATUS_InStored;
            $item->Logisticsname =$this->getSafeParam('logisticName');
            $item->Logistics ='['.$item->Logisticsname.']'. $this->getSafeParam('logistics');
            $item->Userid = $this->getSafeParam('userid');
            $item->Weight = $this->getSafeParam('weight');
            $item->Createdate =  $this->now();
            $item->IsPack = $this->getSafeParam('isPack');
            $item->BignessType =$this->getSafeParam('bignessType');
            $item->VolumeWeight =$this->getSafeParam('volumeWeight');
            $item->CanVacuum =$this->getSafeParam('canVacuum');
            $item->VacuumWeight=$this->getSafeParam('vacuumWeight');
            $item->NoPackageWeight =$this->getSafeParam('noPackageWeight');
            $item->IsEmbargo=$this->getSafeParam('isEmbargo');
            $item->Barcode=$this->getSafeParam('barcode');
            $item->Image = $this->getSafeParam('image');
            $items = $this->getRequest()->getParam('itemType');
            if(is_array($items)){
                $itemType = 0;
                foreach ($items as $type){
                    $itemType = $itemType | intval($type);
                }
                $item->ItemType = $itemType;
            }else{
                $item->ItemType=$this->_getParam('itemType');
                if($item->ItemType==NULL){
                    $item->ItemType=0;
                }
            }
            $item->save();
            $this->content('<a href="/tuan/mystore?userid='.$item->Userid .'">入库成功，查看用户仓库</a>');
        }
    }
    
    public function tipAction(){
        $this->json(array('instore ok',  $this->getSafeParam('id')));
    }


    public function userinfoAction(){
        $this->checkLogin();
        $user = Application_Model_User::getByStoreNo($this->getSafeParam('storeno'));
        if($user==null){
            $this->json(0);
            return;
        }
        $this->json(array('userid'=>$user->Id,'email'=>$user->Email,'nikeName'=>$user->Nikename));
    }
    
        //我的仓库
    /**
     *  我的仓库
     */
    public function mystoreAction() {
        $this->setTitle('我的仓库 | 您的金牌仓库管家');
        $this->appendCss('/css/Share.css'); //    
        $this->appendCss('/css/home/warehouse.css'); //            
        $this->appendScript('/js/jquery.min.js');
        
        $this->setGaCustomVar(1, 'admin', 'true', Uuch_CustomVar::LEVEL_visitor);

        $start = $this->getSafeParam('start');
        if (!$start) {
            $start = 0;
        }

        $userid = $this->getSafeParam('userid');
        $this->view->stores = Application_Model_StoreItem::getMyStore($userid, $this->pageSize, $start);
        $this->view->storelist = $this->view->stores['list'];
    }
    
    /**
     * 运单管理
     */
    public function waybillAction() {
        $this->setTitle('运单管理 |  集中管理，集中配送，更能节省运费');
        $this->appendCss('/css/Share.css'); //    
        $this->appendCss('/css/home/waybill.css'); // 

        $oper = $this->getSafeParam("oper");
        if ($oper == "cancel") {
            //撤消运单
            $id = $this->getSafeParam("id");
            $way = Application_Model_wayBillItem::load($id);
            $way->cancelWay();
            //撤消仓库单
            //Application_Model_StoreItem::cancelForWay($id);
        } else if ($oper == "sign") {
            //确认收货
            $id = $this->getSafeParam("id");
            Application_Model_wayBillItem::sign($id);
        }


        $status = $this->getSafeParam('status');
        $start = $this->getSafeParam('start');
        if (!$start) {
            $start = 0;
        }

        $this->pageSize = 10;

        $userid = $this->getSafeParam('userid');
        $this->view->waybills = Application_Model_wayBillItem::getByFilter(NULL, $userid, date('Y-m-d', strtotime('-10 months')), date('Y-m-d', strtotime('+10 days')), $status, $this->pageSize, $start);

        $this->view->waybilllist = $this->view->waybills['list'];
    }

    
    public function accountAction(){
        
        $this->appendScript('/js/jquery.validate.min.js')->appendScript('/js/messages_cn.js');
        $this->appendCss('/css/daigou/fill.css');
        $userid = $this->getSafeParam('userid');
        $user = Application_Model_User::load($userid);
        $this->view->user = $user;
        if($this->getRequest()->isPost()){
            $account = $user->getAccount();
            $money = $this->getSafeParam('money');
            $history = new Application_Model_UserAccountHistory();
            $history->BeforeMoney = $account->Money;
            $history->AfterMoney = $account->Money -$money;
            $history->BeforeScore = $account->Score;
            $history->AfterScore = $account->Score;
            $history->DateCreated = $this->now();
            $history->Comment = $this->getSafeParam('comment');
            $history->AccountId = $userid;
            $history->Type = 0;
            $history->State = Application_Model_UserAccountHistory::STATE_MONEY;
            $account->Money -= $money;
            $history->save();
            $account->save();
            $this->redirect('tip', 'tuan',array('id'=>$account->Id));
        }
    }
    
        
    public function waybillinfoAction() {
        $this->setTitle('运单管理 |  集中管理，集中配送，更能节省运费');
        $this->appendScript('/js/jquery.validate.min.js')->appendScript('/js/messages_cn.js');
        $this->appendCss('/css/Share.css'); //            

        $this->appendCss('/css/home/waybill.css'); // 

        $id = $this->getSafeParam('id');
        //获取运单信息
        if ($id) {
            $waybill = new Application_Model_wayBillItem($id);

            //获取
            $stores = Application_Model_StoreItem::getBywayId($id);

            $waybill = new Application_Model_wayBillItem($id);
            $this->view->waybill = $waybill;
            $this->view->stores = $stores;
			$this->view->userxx = Application_Model_User::load($waybill->UserId);
            
            $this->view->costs = $waybill->getCostOption();
        }
    }
    
    public function acceptAction(){
        $wayId = $this->getSafeParam('wayId');
        $way = Application_Model_wayBillItem::load($wayId);
        $way->Status = Application_Model_wayBillItem::STATUS_Confrimed;
        $way->save();
        $this->redirect('waybillinfo', 'tuan',array('id'=>$wayId));
    }
    
    public function editpriceAction(){
        $wayId = $this->getSafeParam('wayId');
        $way = Application_Model_wayBillItem::load($wayId);
        $shipMoney = $this->getSafeParam('shipMoney');
        $way->ShipMoney = $shipMoney;
        $way->save();
        $this->redirect('waybillinfo', 'tuan',array('id'=>$wayId));
    }
    
    public function cultfeeAction(){
        $wayId = $this->getSafeParam('wayId');
        $way = Application_Model_wayBillItem::load($wayId);
        $ep = Application_Model_ExpressPrice::load($way->shipFeeconfig);
        $ship = Application_Model_Express::load($way->ShipType);
        
        $weight = $this->getSafeParam('weight');
        $shipFee = $ep->getMoneyByweight($weight);
        $discount = $way->discountFee;
        $serviceFee = 0; //暂时不收服务费
        $shipMoney = $shipFee - $discount + $ship->ReportFee + $serviceFee;
        $this->json(array('shipMoney'=>$shipMoney,'refundMoney'=>$way->ShipMoney - $shipMoney));
    }
    
    public function sendAction(){
        $wayId = $this->getSafeParam('wayId');
        $way = Application_Model_wayBillItem::load($wayId);
        $lastWeight = $this->getSafeParam('lastWeight');
        $lastVolumeWeight = $this->getSafeParam('lastVolumeWeight');
        $lastMoney = $this->getSafeParam('lastMoney');
        $refundMoney = $this->getSafeParam('refundMoney');
        $agentId= $this->getSafeParam('agentId');
        $agentNo = $this->getSafeParam('agentNo');
        
        if($lastVolumeWeight&&$lastVolumeWeight>$lastWeight){
            $way->IsVolume = TRUE;
        }else{
            $way->IsVolume = FALSE;
        }
        
        $way->LastWeight = $lastWeight;
        $way->LastVolumeWeight =$lastVolumeWeight;
        $way->LastMoney=$lastMoney;
        $way->RefundMoney =$refundMoney;
        $way->AgentId=$agentId;
        $way->AgentNo=$agentNo;
        $way->DateSend = $this->now();
        $way->Status = Application_Model_wayBillItem::STATUS_Sended;
        $way->save();
        
        if($refundMoney>0){
            //如果有退款，则改变用户记录
            $user = Application_Model_User::load($way->UserId);
            $account = $user->getAccount();
            $money = $refundMoney;
            $history = new Application_Model_UserAccountHistory();
            $history->BeforeMoney = $account->Money;
            $history->AfterMoney = $account->Money + $money;
            $history->BeforeScore = $account->Score;
            $history->AfterScore = $account->Score;
            $history->DateCreated = $this->now();
            $history->Comment = '运单退款';
            $history->AccountId = $way->UserId;
            $history->Type = 0;
            $account->Money += $money;
            $history->State = Application_Model_UserAccountHistory::STATE_MONEY;
            $history->save();
            $account->save();
        }
        
        $this->redirect('waybillinfo', 'tuan',array('id'=>$wayId));
    }
    
    public function editshipnoAction(){
        $wayId = $this->getSafeParam('wayId');
        $way = Application_Model_wayBillItem::load($wayId);
        $shipType= $this->getSafeParam('shipType');
        $logistics = $this->getSafeParam('logistics');
        $way->Logistics= $logistics;
        $way->ShipType = $shipType;
        $way->CostMoney = $this->getSafeParam('costMoney');
        $way->save();
        $this->redirect('waybillinfo', 'tuan',array('id'=>$wayId));
    }
    
    public function addlogAction(){
        $wayId = $this->getSafeParam('wayId');
        $log = new Application_Model_logisticslogItem();
        $log->WayId = $wayId;
        $log->logisticsNo = '';
        $log->OpDate = $this->getSafeParam('opDate');
        $log->OpRemark = $this->getSafeParam('opRemark');
        $log->OpState = 0;
        $log->opUser = $this->currentUser()->Id;
        $log->save();
        $this->redirect('waybillinfo', 'tuan',array('id'=>$wayId));
    }
    
    public function shipfeeAction(){
        $words = array();
        for($i=0;$i<26;$i++){
            $words []= chr(65+$i);
        }
        $this->view->words = $words;
    }
    
    public function uuchpriceAction(){
        $this->_helper->layout->disableLayout();
        $this->view->express = Application_Model_Express::getAll();
    }

    public function shipfeedetailAction(){
        $cityId = $this->getSafeParam('cityId');
        $weight = $this->getSafeParam('weight');
        if($weight== null || $weight=='')
            $weight=1;
        $this->view->weight = $weight;
        $this->view->costs = Application_Model_ExpressCost::getByCity($cityId,$weight);
        $this->_helper->layout->disableLayout();
    }
    
    public function shipfeepxAction(){
        $cityId = $this->getSafeParam('cityId');
        $weight = $this->getSafeParam('weight');
        if($weight== null || $weight=='')
            $weight=0.5;
        $city = Application_Model_city::load($cityId);
        $word = $city->Word;
        $w0 = $this->get4pxAmount($word, $weight);
        
        $this->_helper->result =$w0;
        $this->_helper->layout->disableLayout();
    }
    
    public function get4pxAmount($word,$weight){
        require_once(APPLICATION_PATH . '/../library/4px/OrderOnlineTools.php');        
        $soap = new OrderOnlineTools();
        //运费试算
        $arrs = array(
                //货物类型(默认：P)(Length = 1)
                "cargoCode" => 'P',
                //目的国家二字代码，参照国家代码表(Length = 2)
                "countryCode" => $word,
                //产品代码,该属性不为空，只返回该产品计费结果，参照产品代码表(Length = 2)
                //"productCode" => array("A1","A6","E5"),
                //计费结果产品显示级别(默认：1)(Length = 1)
                "displayOrder" => '1',
                //邮编(Length <= 10)
                "postCode" => '518000',
                //起运地ID，参照起运地ID表(Length <= 4)
                "startShipmentId" => '10',
                //计费重量，单位(kg)(0 < Amount <= [3,3])
                "weight" => $weight,
                //高(0 < Amount <= [3,3])
                "height" => '2',
                //长(0 < Amount <= [3,3])
                "length" => '2',
                //宽(0 < Amount <= [3,3])
                "width" => '2'
        );
        $result = $soap->chargeCalculateService($arrs);
        
        $result = Uuch_Util::quickArraySort($result['calculateFee'], 'totalRmbAmount');
        return $result;    
    }
    
    public function feeapiAction(){
        $cityId = $this->getSafeParam('cityId');
        $weight = $this->getSafeParam('weight');
        if($weight== null || $weight=='')
            $weight=0.5;
        
        
        $city = Application_Model_city::load($cityId);
        $result = $this->get4pxAmount($city->Word, $weight);
        $this->view->result = $result;
        $this->view->weight = $weight;
        $this->view->express = Application_Model_Express::load($this->getSafeParam('express'))->Description;
        $this->disableLayout();
    }
    
    public function feecostAction(){
        $cityId = $this->getSafeParam('cityId');
        $weight = $this->getSafeParam('weight');
        if($weight== null || $weight=='')
            $weight=0.5;
        
        $expressId = $this->getSafeParam('express');
        //$city = Application_Model_city::load($cityId);
        $result = Application_Model_ExpressCost::getByExpressAndCity($expressId, $cityId, $weight);
        $this->view->costs = $result;
        $this->view->weight = $weight;
        $this->view->express = Application_Model_Express::load($this->getSafeParam('express'))->Description;
        $this->disableLayout();
        
    }
    
    public function myorderAction(){
        $this->setTitle('我的代购订单 | 我的帐户');
        $this->appendCss('/css/home/trade.css');
        $this->appendScript('/js/jquery.min.js');
        $start = $this->getSafeParam('start');
        if(!$start)
            $start=0;
        
        $memberId =  $this->getSafeParam('userid');
        $status = $this->getSafeParam('status');
        $this->view->orders = Application_Model_Order::getByFilter(NULL,$memberId,null, null,$status,null,  $this->pageSize, $start);
        $ships = Application_Model_shipType::getAll();
        $shipsa = Uuch_Util::quickSort($ships, 'word');
        $result =array(''=>'');
        foreach ($shipsa as $item)
            $result[$item->Id] = $item->Word . '_' . $item->Name;
        $this->view->shipTypes = $result;
        $this->view->orderList = $this->view->orders['list'];
    }
    
    public function setorderAction(){
        $orderid =  $this->getSafeParam('orderid');
        $status = $this->getSafeParam('status');
        $order = Application_Model_Order::load($orderid);
        $order->Status = $status;
        $order->save();
        $this->redirect('myorder', 'tuan');
    }
    
    public function setordernoAction(){
        $orderid =  $this->getSafeParam('orderid');
        $order = Application_Model_Order::load($orderid);
        $order->ProcureNo = $this->getSafeParam('ProcureNo');
        $order->logistics = $this->getSafeParam('logistics');
        $order->LogisticsNo = $this->getSafeParam('LogisticsNo');
        $order->save();
        $this->redirect('myorder', 'tuan');
    }
}


